<?php
declare (strict_types=1);

namespace app\data\model;

use think\model\Pivot;

/**
 * 拓展分类关联关系表
 * @mixin \think\Model
 */
class ProductsExtCatRelationsModel extends Pivot
{
    protected $table = 'ctmon_products_ext_cat_relations';
    protected $pk = 'id';

    protected $schema = [
        'id' => 'bigint',
        'product_id' => 'int',
        'cat_id' => 'int',
    ];

    /**
     *
     * 分页查询，后台使用
     *
     * @param int $page_index 第几页
     * @param int $page_size 每页几条数据
     * @param array $where 查询条件
     * @param string $field 查询字段
     * @param string $order 排序字段
     * @param array $withs 关联查询
     * @return array 返回数组数据
     */
    public function pages(int $page_index = 1, int $page_size = 10, array $where = [], string $field = '*', string $order = '', array $withs = []): array
    {
        $count = $this
            ->where($where)
            ->count();


        $start = $page_size * ($page_index - 1);
        $stmt = $this
            ->where($where)
            ->field($field)
            ->order($order)
            ->limit($start, $page_size);
        if (count($withs) > 0) {
            $stmt = $stmt->with($withs);
        }
        $data = $stmt
            ->select()
            ->toArray();

        $totalPage = $count % $page_size == 0 ? $count / $page_size : ceil($count / $page_size);

        return [
            'page_index' => $page_index + 1,
            'count' => $count,
            'list' => $data,
            'totalPage' => intval($totalPage),
            'pageInfo' => [
                'pageIndex' => $page_index,
                'pageSize' => $page_size,
                'totalPage' => $totalPage,
                'total' => $count,
            ]
        ];
    }


    /**
     *
     * 获取多条数据
     *
     * @param array $where 查询条件
     * @param string $field 查询字段
     * @param string $order 排序字段
     * @return array 返回数组数据
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function findAll(array $where = [], string $field = '*', string $order = '', array $with = []): array
    {
        $stmt = $this
            ->where($where)
            ->field($field);
        if ($with) {
            $stmt = $stmt->with($with);
        }
        return $stmt
            ->order($order)
            ->select()
            ->toArray();
    }
}
